package cn.car91.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.activity.BaseFragmentActivity;
import cn.car91.activity.MapNavigatorActivity;
import cn.car91.bean.RepairShop;
import cn.car91.bean.Service;
import cn.car91.config.InitApplication;
import cn.car91.utils.ImageManager;
import cn.car91.utils.MobileOperationUtil;
import cn.car91.utils.RegexUtil;
import cn.car91.view.MyListView;
import cn.car91.view.XListView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.BNaviPoint;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BaiduNaviManager.OnStartNavigationListener;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams.NE_RoutePlan_Mode;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.util.LogUtils;

public class RepairShopListAdapter extends ArrayAdapter {
    private int resource;
    private LayoutInflater layoutInflater;
    private List<RepairShop> data;
    static ImageManager imageManager;

    private boolean showWash = false;

    public boolean isShowWash() {
        return showWash;
    }
    public void setShowWash(boolean showWash) {
        this.showWash = showWash;
    }
    
    public List<RepairShop> getData() {
        return data;
    }

    public void setData(List<RepairShop> data) {
        this.data = data;
    }

    public void addData(List<RepairShop> data) {
        this.data.addAll(data);
    }

    public void removeData(int index){
    	this.data.remove(index);
    }
    
    private InitApplication config;

    public RepairShopListAdapter(Context context, int resource) {
        super(context, resource);
        this.resource = resource;
        this.layoutInflater = LayoutInflater.from(context);
        config = (InitApplication) context.getApplicationContext();
        this.data = new ArrayList<RepairShop>();

        imageManager = new ImageManager(getContext(), "sdcard/car91/temp/repairshop");
    }

    public final class RepairShopItem {
        /*public TextView id;*/
        public ImageView image;
        public TextView title;
        public TextView address;
        public TextView info;
        public ImageView rank;
        public TextView good;
        public TextView distance;
        public TextView rgrade;
        public TextView phone;
        public TextView position;
        public View wash;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return data.get(arg0);
    }

    public String getRepairShopId(int which){
    	return data.get(which).getId();
    }
    
    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        // TODO Auto-generated method stub
        RepairShopItem repairShopItem = null;
        if (arg1 == null) {
            repairShopItem = new RepairShopItem();

            arg1 = layoutInflater.inflate(resource, null);
            /*repairShopItem.id = (TextView) arg1.findViewById(R.id.repairshop_item_id);*/
            repairShopItem.image = (ImageView) arg1.findViewById(R.id.repairshop_item_pic);
            repairShopItem.title = (TextView) arg1.findViewById(R.id.repairshop_item_info_title);
            try {
//                repairShopItem.good = (TextView) arg1.findViewById(R.id.repairshop_item_info_good);
                repairShopItem.info = (TextView) arg1.findViewById(R.id.repairshop_item_info_extra_content);
                repairShopItem.address = (TextView) arg1.findViewById(R.id.repairshop_item_info_address_content);
            } catch (Exception e) { }
            repairShopItem.rgrade = (TextView) arg1.findViewById(R.id.repairshop_item_info_rgrade);
            repairShopItem.distance = (TextView) arg1.findViewById(R.id.repairshop_item_info_distance);
            repairShopItem.rank = (ImageView) arg1.findViewById(R.id.repairshop_item_info_rank);
            repairShopItem.position = (TextView) arg1.findViewById(R.id.repairshop_item_info_position);
            repairShopItem.phone = (TextView) arg1.findViewById(R.id.repairshop_item_info_phone);
            repairShopItem.wash = arg1.findViewById(R.id.repairshop_item_info_wash);

            arg1.setTag(repairShopItem);
            
            initData(repairShopItem,(RepairShop) getItem(arg0),arg2);
        } else {
            repairShopItem = (RepairShopItem) arg1.getTag();
        }

        /*repairShopItem.id.setText(repairShop.getId());*/
        
        
        return arg1;
    }

    
    private void initData(RepairShopItem repairShopItem,final RepairShop repairShop,ViewGroup arg2) {
        repairShopItem.title.setText(Html.fromHtml(repairShop.getName()));
        if(repairShop.getDetail().getRank()!=null&&repairShop.getDetail().getRank()>0) {
          repairShopItem.rank.setVisibility(View.VISIBLE);
        }

        if(repairShop.getDetail().getRepairgrade()!=null){
          switch (repairShop.getDetail().getRepairgrade()) {
          case 0:
            repairShopItem.rgrade.setText("资质：普通");
            break;
          case 1:
            repairShopItem.rgrade.setText("资质：一类");    
            break;
          case 2:
            repairShopItem.rgrade.setText("资质：二类");
            break;
          default:
            repairShopItem.rgrade.setText("资质：三类");
            break;
          }
        }
        
        try {
          BDLocation location = ((BaseFragmentActivity)layoutInflater.getContext()).getCar91Application().getmLocationClient().getLastKnownLocation();
          LatLng curLatLng = new LatLng(location.getLatitude(), location.getLongitude());
          
          String[] dtmp = repairShop.getDetail().getPosition().split(",");
          double lon = Double.valueOf(dtmp[0]);
          double lat = Double.valueOf(dtmp[1]);
          LatLng latLng = new LatLng(lat, lon);
          double distance = DistanceUtil.getDistance(curLatLng, latLng);
          
          if(distance > 5000){
            repairShopItem.distance.setText(String.format("%.1f", distance/1000)+"km");
          }else{
            int dis;
            dis = (int)distance;
            repairShopItem.distance.setText(dis+"m");
          }
        } catch (Exception e) { 
          repairShopItem.distance.setText("");
        }
        
        try {
            if(showWash) {
                for (Service service : repairShop.getDetail().getServices()) {
                    if(8==service.getSid()){
                        repairShopItem.wash.setVisibility(View.VISIBLE);
                        break;
                    }
                }
            }
        } catch (Exception e) { }
        
        String picImg = config.getCenterServerUrl() + "/" + repairShop.getLogo();
        try {
            int index = repairShop.getLogo().lastIndexOf("/");
            picImg = config.getCenterServerUrl() + "/" + repairShop.getLogo().substring(0, index) + "/imgco" + repairShop.getLogo().substring(index, repairShop.getLogo().length());
        } catch (Exception e) { }
        imageManager.displayImage(picImg, repairShopItem.image, getContext().getResources().getDrawable(R.drawable.load_error));

        if (arg2 instanceof XListView) {
            ((MyListView) arg2).setOnScrollListener(new PauseOnScrollListener(imageManager.getBitmapUtils(), true, true));
        } else if (arg2 instanceof GridView) {
            ((GridView) arg2).setOnScrollListener(new PauseOnScrollListener(imageManager.getBitmapUtils(), true, true));
        }

        try {
            Long count = repairShop.getCommentcount();
            int good = 100;
            if (cn.car91.utils.RegexUtil.isNotNull(count)) {
                good = (int) ((repairShop.getGoodcount() * 1.0 / count) * 100);
            }
            //repairShopItem.good.setText("好评率："+good+"%");
            repairShopItem.info.setText(good + "%");
        } catch (Exception e) { }
        /*StringBuffer serviceStr = new StringBuffer();
    Set<Service> services = repairShop.getDetail().getServices();
    if(services!=null){
      for (Service service : services) {
        serviceStr.append(service.getName()+" ");
      }
    }*/
        //repairShopItem.info.setText(serviceStr);
        try {
            repairShopItem.address.setText(repairShop.getDetail().getAddress());
        } catch (Exception e) { }
        
        try {
          repairShopItem.phone.setText(repairShop.getDetail().getPhone());
        } catch (Exception e) { } 
        finally {
          ((View)repairShopItem.phone.getParent()).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
              if (RegexUtil.isNotNull(repairShop.getDetail().getPhone())) {
                try {
                    MobileOperationUtil.callPhone(layoutInflater.getContext(), repairShop.getDetail().getPhone());
                } catch(Exception e) { }
              }
            }
          });
        }
        
        try {
          repairShopItem.position.setText(repairShop.getDetail().getPosition());
        } catch (Exception e) { }
        finally {
          ((View)repairShopItem.position.getParent()).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
              if(RegexUtil.isNotNull(repairShop.getDetail().getPosition())) {
                try {
                  String pointString = repairShop.getDetail().getPosition();
                  String[] points = pointString.split(",");
                  
                  BDLocation location = ((BaseFragmentActivity)layoutInflater.getContext()).getCar91Application().getmLocationClient().getLastKnownLocation();
                  BNaviPoint startPoint = new BNaviPoint(location.getLongitude(), location.getLatitude(), "我的位置", BNaviPoint.CoordinateType.BD09_MC);
                  BNaviPoint endPoint = new BNaviPoint(Double.valueOf(points[0]), Double.valueOf(points[1]), repairShop.getName(), BNaviPoint.CoordinateType.BD09_MC);
                  BaiduNaviManager.getInstance().launchNavigator((Activity) layoutInflater.getContext(),
                          startPoint, endPoint,
                          NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME,       //算路方式  
                          true,                                            //真实导航  
                          BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, //在离线策略  
                          new OnStartNavigationListener() {                //跳转监听  
                              @Override
                              public void onJumpToNavigator(Bundle configParams) {
                                  Intent intent = new Intent(layoutInflater.getContext(), MapNavigatorActivity.class);
                                  intent.putExtras(configParams);
                                  layoutInflater.getContext().startActivity(intent);
                              }
  
                              @Override
                              public void onJumpToDownloader() {
                              }
                          });
                  } catch (Exception e2) { 
                      LogUtils.e(e2.getMessage());
                  }
              }
            }
          });
        }
    }
}
